package onnxruntime

import (
	"errors"
	"unsafe"
)

// #cgo CFLAGS: -O2 -g
//
// #include "onnxruntime_wrapper.h"
import "C"

// Used when setting key-value pair options with certain obnoxious C APIs.
// The entries in each of the returned slices must be freed when they're
// no longer needed.
func mapToCStrings(options map[string]string) ([]*C.char, []*C.char) {
	keys := make([]*C.char, 0, len(options))
	values := make([]*C.char, 0, len(options))
	for k, v := range options {
		keys = append(keys, C.CString(k))
		values = append(values, C.CString(v))
	}
	return keys, values
}

// Calls free on each entry in the array of C strings.
func freeCStrings(s []*C.char) {
	for i := range s {
		C.free(unsafe.Pointer(s[i]))
		s[i] = nil
	}
}

// Does two things: converts the given OrtStatus to a Go error, and releases
// the status. If the status is nil, this does nothing and returns nil.
func statusToError(status *C.OrtStatus) error {
	if status == nil {
		return nil
	}
	msg := C.GetErrorMessage(status)
	toReturn := C.GoString(msg)
	C.ReleaseOrtStatus(status)
	return errors.New(toReturn)
}
